<template>
  <div class="alloc-menu">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>分配菜单</span>
        </div>
      </template>
      <el-tree
        ref="treeMenu"
        node-key="id"
        :data="menus"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedKeys"
      />
      <div style="text-align: center;">
        <el-button @click="resetChecked">清空</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '/@/services/Menu'
import { ElTree, ElMessage } from 'element-plus'
import router from '/@/router/Index'
export default defineComponent({
  name: 'AllocMenu',
  components: {},
  props: {
    roleId: {
      type: [String, Number],
      default: ''
    }
  },
  setup(props: any, context: any) {
    const menus = ref([])
    const defaultProps = ref({
      children: 'subMenuList',
      label: 'name'
    })
    const loadMenus = async () => {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        menus.value = data.data
      }
    }
    const onSave = async () => {
      const menuIdList = (treeMenu.value as ElTree).getCheckedKeys()
      const { data } = await allocateRoleMenus({
        roleId: props.roleId,
        menuIdList
      })
      if (data.code === '000000') {
        ElMessage.success('操作成功')
        router.back()
      } else {
        ElMessage.error('操作失败')
      }
    }
    const treeMenu = ref(null)
    const checkedKeys = ref([])
    const getCheckedKeys = (menus: any) => {
      menus.forEach((menu: any) => {
        if (menu.subMenuList) {
          getCheckedKeys(menu.subMenuList)
        } else if (menu.selected) {
          // checkedKeys.value.push(menu.id as never)
          checkedKeys.value = [...checkedKeys.value, menu.id] as never
        }
      })
    }
    const loadRoleMenus = async () => {
      const { data } = await getRoleMenus(props.roleId)
      // console.log(data.data)
      if (data.code === '000000') {
        getCheckedKeys(data.data)
      }
    }
    const resetChecked = () => {
      const elTree = treeMenu.value as ElTree
      elTree.setCheckedKeys([])
    }
    return {
      menus,
      defaultProps,
      loadMenus,
      onSave,
      treeMenu,
      loadRoleMenus,
      checkedKeys,
      getCheckedKeys,
      resetChecked
    }
  },
  data() {
    return {}
  },
  created() {
    this.loadMenus()
    this.loadRoleMenus()
  }
})
</script>
<style lang="scss" scoped></style>
